package cn.itcast.bos.web.base.action;

import domain.base.Area;
import domain.base.Courier;
import domain.base.Standard;
import cn.itcast.bos.service.base.AreaService;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.*;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/12/012.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class AreaAction extends BaseAction<Area,AreaService>{
    //设置接收文件
    private File file;
    //模型驱动
    private Area area = new Area();
    //接受分页信息
    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public void setFile(File file) {
        this.file = file;
    }



    @Action(value = "area_pageQuery",results = {@Result(name = "success",type = "json")})
    public String pageQuery(){
        Specification<Courier> specification = new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //如果第一个查询条件不为空
                if (StringUtils.isNotBlank(area.getProvince())){
                    //断言 表达的是Where 之后的语句,这里相当于是动态拼接SQL语句
                    //等于name = %?%,xxx
                    Predicate p1 = cb.like(root.get("province").as(String.class),'%'+area.getProvince()+'%');
                    list.add(p1);
                }
                if(StringUtils.isNotBlank(area.getCity())){
                    //这里可以用like进行模糊查询
                    Predicate p2 = cb.like(root.get("city").as(String.class),'%'+area.getCity()+'%');
                    list.add(p2);
                }
                if(StringUtils.isNotBlank(area.getDistrict())){
                    //这里可以用like进行模糊查询
                    Predicate p3 = cb.like(root.get("district").as(String.class),'%'+area.getDistrict()+'%');
                    list.add(p3);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        //封装page和row信息
        Pageable pageable = new PageRequest(page-1,rows);
        //通过继承JpaSpecification接口使其findAll方法获得带条件检索功能
        Page<Courier> pageData = service.findPageData(specification,pageable);

        Map<String,Object> result = new HashMap<>();
        result.put("total",pageData.getNumberOfElements());
        result.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(result);

        return SUCCESS;
    }

    @Action(value = "area_batchImport")
    public String batchImport() throws IOException, PinyinException {
        List<Area> areas = new ArrayList<>();
        //基于.xls格式解析HSSF
        //加载Excel文件对象
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
        HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
        //读取每一行
        for(Row row :sheet){
            //第一行跳过
            if (row.getRowNum()==0){
                continue;
            }
            //跳过空行
            if (row.getCell(0)==null||
                    StringUtils.isBlank(row.getCell(0).getStringCellValue())){
                continue;
            }
            Area area = new Area();
            area.setId(row.getCell(0).getStringCellValue());
            area.setProvince(row.getCell(1).getStringCellValue());
            area.setCity(row.getCell(2).getStringCellValue());
            area.setDistrict(row.getCell(3).getStringCellValue());
            area.setPostcode(row.getCell(4).getStringCellValue());

            //简码与城市编码===jpingyin
            //获取省市区
            String province = area.getProvince();
            String city = area.getCity();
            String district = area.getDistrict();
            //去除最后一位单位（省，市 ，区）
            province = province.substring(0, province.length() - 1);
            city = city.substring(0, city.length() - 1);
            district = district.substring(0, district.length() - 1);
            //简码与城市编码===jpingyin
            String citycode = PinyinHelper.convertToPinyinString(city,"", PinyinFormat.WITHOUT_TONE);
            String shortcode = PinyinHelper.getShortPinyin(province+city+district);
            area.setCitycode(citycode);
            area.setShortcode(shortcode);
            areas.add(area);


            areas.add(area);

        }
        service.batchImport(areas);
        return NONE;
    }

    @Override
    public Area getModel() {
        return area;
    }
}
